﻿CREATE PROCEDURE [ServiceEngine].[CreateSchemaObject]
@schemaID UNIQUEIDENTIFIER, @schemaObjectType SMALLINT, @schemaObjectName NVARCHAR (256), @schemaObjectXml XML, @parentID UNIQUEIDENTIFIER=NULL, @ID UNIQUEIDENTIFIER OUTPUT
AS
BEGIN
	DECLARE @ErrorMessage NVARCHAR(4000);
	DECLARE @ErrorSeverity INT;
	DECLARE @ErrorState INT;
	DECLARE @ExistID UNIQUEIDENTIFIER;
	
	SET NOCOUNT ON;

	IF @ID IS NULL
	BEGIN
		SELECT @ExistID = [SchemaObjectID] FROM [SchemaObjects] WHERE [SchemaID] = @schemaID AND [SchemaObjectName] = @schemaObjectName AND @schemaObjectType = [SchemaObjectType] AND DateRevised IS NULL
	END
	
	BEGIN TRY
		IF @ExistID IS NULL
		BEGIN				
			SET @ID = newid();
			BEGIN TRANSACTION
				INSERT INTO [SchemaObjects]
						   ([SchemaObjectID]
						   ,[SchemaID]
						   ,[SchemaObjectType]
						   ,[SchemaObjectName]
						   ,[SchemaObjectXml])
					 VALUES
						   (@ID
						   ,@schemaID
						   ,@schemaObjectType
						   ,@schemaObjectName
						   ,@schemaObjectXml)
						   
				IF (@parentID IS NOT NULL)
				BEGIN
					INSERT INTO [SchemaObjectDependencies]
						   ([SchemaObjectDependencyID]
						   ,[SchemaObjectID]
						   ,[ParentObjectID])
					 VALUES
						   (newID()
						   ,@ID
						   ,@parentID)
				END
			COMMIT TRANSACTION
		END
		ELSE
		BEGIN
			SET @ErrorMessage = 'SchemaObject with ID = [' + CAST(@ID AS nvarchar) + '] already exists'
			RAISERROR (@ErrorMessage, 
				   16,
				   1);
		END
	END TRY
	BEGIN CATCH
		SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();

		IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;

		RAISERROR (@ErrorMessage, 
				   @ErrorSeverity,
				   1);
	END CATCH
END

